package com.ibangnuo.manage.service.system;

import com.alibaba.fastjson.JSONObject;
import com.ibangnuo.framework.domain.system.SysDictionary;
import com.ibangnuo.framework.exception.ExceptionCast;
import com.ibangnuo.framework.model.response.*;
import com.ibangnuo.framework.redisKey.Rediskey;
import com.ibangnuo.manage.dao.system.SysDictionaryRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Author: wwy
 * @Date: 2019-12-21 9:21
 */
@Service
public class SysDictionaryService {
    private static Logger LOGGER = LoggerFactory.getLogger(SysDictionaryService.class);
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private ValueOperations valueOperations;
    @Autowired
    private SysDictionaryRepository sysDictionaryRepository;
    private static String[] mapKey;
    static {
        SysDictionary sysDictionary = new SysDictionary();
        sysDictionary.setId("1");
        sysDictionary.setName("1");
        sysDictionary.setType("1");
        sysDictionary.setValue("1");
        String mapJson = JSONObject.toJSONString(sysDictionary);
        List<String> list = new ArrayList<>();
        Map<String,String> map = JSONObject.parseObject(mapJson, Map.class);
        for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
            list.add(stringStringEntry.getKey());
        }
        mapKey = new String[list.size()];
        mapKey = list.toArray(mapKey);

    }
    /**
     * 查询全部
     * @return
     */
    public QueryResponseResult findAll(){
        List<SysDictionary> all = sysDictionaryRepository.findAll();
        QueryResult queryResult = new QueryResult();
        queryResult.setList(all);
        queryResult.setTotal(all.size());
        return new QueryResponseResult(CommonCode.SUCCESS,queryResult);
    }

    /**
     * 保存为hash结构
     * id为主键
     * key为类型，并且保存一个key=name为类型名称
     * 1.保存进入数据库
     * @param sysDictionary
     * @return
     */
    public ResponseResult add(SysDictionary sysDictionary){
        sysDictionaryRepository.save(sysDictionary);
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 根据id查找
     * @param id
     * @return
     */
    public ObjectResult<Map> findById(String id){
        try {
            String keyId = Rediskey.SYSDICTIONARY+id;
            LOGGER.info("rideskey:{}",keyId);
            Map<Object, Object> sysDicMap = redisTemplate.opsForHash().entries(keyId);
            if(sysDicMap == null || sysDicMap.size()<=0){
                Optional<SysDictionary> optional = sysDictionaryRepository.findById(id);
                if(!optional.isPresent()){
                    return new ObjectResult<Map>(CommonCode.FAIL,null);
                }
                SysDictionary sysDictionary = optional.get();
                String sysDicStrJson = JSONObject.toJSONString(sysDictionary);
                sysDicMap = JSONObject.parseObject(sysDicStrJson, Map.class);
                redisTemplate.opsForHash().putAll(keyId,sysDicMap);
            }
            return new ObjectResult<>(CommonCode.SUCCESS,sysDicMap);
        } catch (Exception e) {
            LOGGER.info("缓存库连接异常:{}",e.getMessage());
            Optional<SysDictionary> optional = sysDictionaryRepository.findById(id);
            if(!optional.isPresent()){
                return new ObjectResult<Map>(CommonCode.FAIL,null);
            }
            return new ObjectResult(CommonCode.SUCCESS,optional.get());
        }
    }

    /**
     * 根据type查找
     * @param type
     * @return
     */
    public ObjectResult findByType(String type){
        try {
            String keyId = Rediskey.SYSDICTIONARY_TYPE+type;
            LOGGER.info("rideskey:{}",keyId);
            Map<Object, Object> sysDicMap = redisTemplate.opsForHash().entries(keyId);
            if(sysDicMap == null || sysDicMap.size()<=0){
                SysDictionary sysDictionary = sysDictionaryRepository.findByType(type);
                if(sysDictionary==null){
                    return new ObjectResult<Map>(CommonCode.FAIL,null);
                }
                String sysDicStrJson = JSONObject.toJSONString(sysDictionary);
                sysDicMap = JSONObject.parseObject(sysDicStrJson, Map.class);
                redisTemplate.opsForHash().putAll(keyId,sysDicMap);
            }
            return new ObjectResult<>(CommonCode.SUCCESS,sysDicMap);
        } catch (Exception e) {
            LOGGER.info("缓存库连接异常:{}",e.getMessage());
            SysDictionary sysDictionary = sysDictionaryRepository.findByType(type);
            if(sysDictionary==null){
                return new ObjectResult<Map>(CommonCode.FAIL,null);
            }
            return new ObjectResult(CommonCode.SUCCESS,sysDictionary);
        }
    }

    /**
     * 根据id删除
     * 1.删除数据库
     * 2.删除缓存
     * @param id
     * @return
     */
    public ResponseResult delete(String id){
        SysDictionary sysDictionary = this.getById(id);
        String keyId = Rediskey.SYSDICTIONARY+id;
        String keyTypeId = Rediskey.SYSDICTIONARY_TYPE+sysDictionary.getType();
        sysDictionaryRepository.deleteById(id);
        try {
            redisTemplate.opsForHash().delete(keyId,mapKey);
            redisTemplate.opsForHash().delete(keyTypeId,mapKey);
        } catch (Exception e) {
            LOGGER.info("缓存库连接异常{}",e.getMessage());
        }
        return new ResponseResult(CommonCode.SUCCESS);
    }

    /**
     * 根据id更新
     * 1.更新数据库
     * 2.删除缓存
     * @param id
     * @param sysDictionary
     * @return
     */
    public ResponseResult update(String id,SysDictionary sysDictionary){
        String keyId = Rediskey.SYSDICTIONARY+id;
        SysDictionary one = this.getById(id);
        String keyTypeId = Rediskey.SYSDICTIONARY_TYPE+one.getType();
        if(one!=null){
            one.setName(sysDictionary.getName());
            one.setType(sysDictionary.getType());
            one.setValue(sysDictionary.getValue());
            sysDictionaryRepository.save(one);
            try {
                redisTemplate.opsForHash().delete(keyId,mapKey);
                redisTemplate.opsForHash().delete(keyTypeId,mapKey);
            } catch (Exception e) {
                LOGGER.info("缓存库连接异常{}",e.getMessage());
            }
            return new ResponseResult(CommonCode.SUCCESS);
        }
        return new ResponseResult(CommonCode.FAIL);
    }

    /**
     * 根据id查询
     * @return
     */
    public SysDictionary getById(String id){
        Optional<SysDictionary> optional = sysDictionaryRepository.findById(id);
        if(optional.isPresent()){
            return optional.get();
        }
        return null;
    }

}
